﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using WPControla.Client.Entities;

namespace WPControla.Client.Services.Rss
{
    public class RssService : IRssService
    {
        private WebClient webClient;

        public void GetRssData(Uri source)
        {
            webClient = new WebClient();
            webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(OnOpenReadCompleted);
            webClient.OpenReadAsync(source);
        }

        void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                EndDownloadRss(e.Result);
            }
        }

        void EndDownloadRss(Stream value)
        {
            XDocument doc = XDocument.Load(value);

            List<RssItem> items = new List<RssItem>();

            var list = doc.Element("rss").Element("channel").Elements("item");
            XNamespace content = XNamespace.Get("http://purl.org/rss/1.0/modules/content/");
            foreach (var item in list)
            {
                items.Add(new RssItem()
                {
                    Title = item.Element("title").Value,
                    DateTime = DateTime.Parse(item.Element("pubDate").Value),
                    Content = item.Element("description").Value
                });
            }

            Entities.Rss rss = new Entities.Rss()
            {
                Tile = doc.Element("rss").Element("channel").Element("title").Value,
                Items = new List<RssItem>(items)
            };


            var handler = RssDownloadCompleted;
            if (handler != null)
            {
                handler(this, new RssDownloadEventArgs(rss));
            }
        }

        public event EventHandler<RssDownloadEventArgs> RssDownloadCompleted;
    }
}
